<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="材质名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="材质名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['vt:vt-material:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['vt:vt-material:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="name" label="材质名称" prop="name" min-width="150" align="center" />
        <el-table-column
          key="density"
          label="密度值（千克/立方米）"
          prop="density"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="thickness"
          label="厚度值（米）"
          prop="thickness"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="unitPrice"
          label="单价（元/千克）"
          prop="unitPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="editable"
          label="厚度可调"
          prop="editable"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.editable == 1" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['vt:vt-material:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['vt:vt-material:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 材质信息表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="材质名称" prop="name">
          <el-input v-model="formData.name" placeholder="材质名称" />
        </el-form-item>

        <el-form-item label="密度值（千克/立方米）" prop="density">
          <el-input-number v-model="formData.density" placeholder="密度值（千克/立方米）" />
        </el-form-item>

        <el-form-item label="厚度值（米）" prop="thickness">
          <el-input-number v-model="formData.thickness" placeholder="厚度值（米）" />
        </el-form-item>

        <el-form-item label="单价（元/千克）" prop="unitPrice">
          <el-input-number v-model="formData.unitPrice" placeholder="单价（元/千克）" />
        </el-form-item>

        <el-form-item label="厚度可调" prop="editable">
          <el-switch v-model="formData.editable" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: "VtMaterial",
  inheritAttrs: false,
});

import VtMaterialAPI from "@/api/vt/vt-material.js";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 材质信息表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 材质信息表单数据
const formData = reactive({});

// 材质信息表单校验规则
const rules = reactive({});

/** 查询材质信息 */
function handleQuery() {
  loading.value = true;
  VtMaterialAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置材质信息查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开材质信息弹窗 */
function handleOpenDialog(id) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改材质信息";
    VtMaterialAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增材质信息";
  }
}

/** 提交材质信息表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        VtMaterialAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        VtMaterialAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭材质信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除材质信息 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      VtMaterialAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
